package org.jeecg.modules.room.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.room.entity.*;
import org.jeecg.modules.room.mapper.RoomBookRoomMapper;
import org.jeecg.modules.room.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 预定单和房间号对应表
 * @Author: jeecg-boot
 * @Date:   2023-12-18
 * @Version: V1.0
 */
@Service
public class RoomBookRoomServiceImpl extends ServiceImpl<RoomBookRoomMapper, RoomBookRoom> implements IRoomBookRoomService {

    @Autowired
    private IRoomBookInfoMxService roomBookInfoMxService;
    @Autowired
    private IRoomBookInfoService roomBookInfoService;
    @Autowired
    private IRoomInfoService roomInfoService;
    @Autowired
    private IRoomTypeService roomTypeService;

    /**
     * 手动分房
     * @param bookMxIds
     * @param roomCodeList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addFp(String bookMxIds,List<RoomInfo> roomCodeList,String bookCode) {
        try {
            String[] bookMxArr = bookMxIds.split(",");
            Boolean updateStatusFlag = false;

            RoomBookInfo roomBookInfo = roomBookInfoService.getOne(new QueryWrapper<RoomBookInfo>().eq("book_code",bookCode));

            if(!roomBookInfo.getBookStatus().equals("10"))
            {
                throw new JeecgBootException("预定单号:" + roomBookInfo.getBookCode() +"当前状态不能分配房间!");
            }
            //分配房间
            for(String bookMxId : bookMxArr){
                Long count = this.baseMapper.selectCount(new QueryWrapper<RoomBookRoom>().eq("book_mx_id",bookMxId)); //判断是不是已经分配房间了，防止并发操作
                if(count>0){
                    continue;
                }
                RoomBookInfoMx roomBookInfoMx = roomBookInfoMxService.getById(bookMxId);
                int loopBookRoom = 0;
                for (int j=0;j< roomCodeList.size();j++) {
                    if(roomCodeList.get(j).getRoomTypeCode().equals(roomBookInfoMx.getRoomTypeCode())){ //判断所选房间类型和预定单明细是否一致
                        if(loopBookRoom < roomBookInfoMx.getBookRoomNum()){  //限定所选房间数不能超过预定房间数
                                RoomBookRoom roomBookRoom = new RoomBookRoom();
                                roomBookRoom.setBookMxId(roomBookInfoMx.getId());
                                roomBookRoom.setId(UUIDGenerator.generate());
                                roomBookRoom.setRoomCode(roomCodeList.get(j).getRoomCode());
                                this.baseMapper.insert(roomBookRoom);
                                roomCodeList.remove(roomCodeList.get(j)); //将该房间从列表中移除，防止多次添加
                                loopBookRoom ++ ;
                                //更改房间分配状态
                                updateStatusFlag = true;
                        }
                    }
                }
            }

            //修改状态为已分房
            if(updateStatusFlag) {
                roomBookInfo.setBookStatus("20");
                roomBookInfoService.update(roomBookInfo, new QueryWrapper<RoomBookInfo>().eq("book_code", bookCode));
            }

        }
        catch (Exception e){
            throw e;
        }
    }

    /**
     * 自动分房
     * @param bookMxIds
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoFpRoom(String bookMxIds,String bookCode) {
        try {
            String[] bookMxIdArr = bookMxIds.split(",");
            Boolean updateStatusFlag = false;
            RoomBookInfo roomBookInfo = roomBookInfoService.getOne(new QueryWrapper<RoomBookInfo>().eq("book_code",bookCode));

            if(!roomBookInfo.getBookStatus().equals("10"))
            {
                throw new JeecgBootException("预定单号:" + roomBookInfo.getBookCode() +"当前状态不能分配房间!");
            }
            //分配房间
            for (String bookMxId : bookMxIdArr) {
                Long count = this.baseMapper.selectCount(new QueryWrapper<RoomBookRoom>().eq("book_mx_id",bookMxId));
                if(count>0){
                    continue;
                }
                RoomBookInfoMx roomBookInfoMx = roomBookInfoMxService.getById(bookMxId);
                //查询可用房间
                Page<RoomInfo> page = new Page<RoomInfo>(1, 1000);
                IPage<RoomInfo> roomInfoList = roomInfoService.selectUsableRoomList(page,roomBookInfoMx.getRoomTypeCode(), "", "", "", "", roomBookInfo.getDateArrival().toString(), roomBookInfo.getDateDeparture().toString());

                //分配房间 插入房间号
                RoomBookRoom roomBookRoom = new RoomBookRoom();
                roomBookRoom.setBookMxId(bookMxId);
                for (int i = 0; i < roomBookInfoMx.getBookRoomNum(); i++) {
                    if(roomInfoList.getRecords().size() !=0 && roomInfoList.getRecords().get(i) != null) {
                        roomBookRoom.setId(UUIDGenerator.generate());
                        roomBookRoom.setRoomCode(roomInfoList.getRecords().get(i).getRoomCode());
                        this.baseMapper.insert(roomBookRoom);
                        //更改房间分配状态
                        updateStatusFlag = true;
                    }
                }

            }
            if(updateStatusFlag) {
                //修改状态为已分房
                roomBookInfo.setBookStatus("20");
                roomBookInfoService.update(roomBookInfo, new QueryWrapper<RoomBookInfo>().eq("book_code", bookCode));
            }
        }
        catch (Exception e){
            throw e;
        }
    }

    /**
     * 自动分房
     * @param bookCodes
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoFpRoomByBookCode(String bookCodes) {
        try {
            String[] bookCodesArr = bookCodes.split(",");
            for(String bookCode : bookCodesArr){
                List<String> mxIdList = new ArrayList<>();
                List<RoomBookInfoMx> roomBookInfoMxList = roomBookInfoMxService.list(new QueryWrapper<RoomBookInfoMx>().eq("book_code",bookCode));
                for(RoomBookInfoMx roomBookInfoMx : roomBookInfoMxList){
                    mxIdList.add(roomBookInfoMx.getId());
                }
                autoFpRoom(String.join(",", mxIdList),bookCode);
            }
        }
        catch (Exception e){
            throw e;
        }
    }

    /**
     * 取消分房
     * @param bookMxIds
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelFp(String bookMxIds,String bookCode) {
        try {

            RoomBookInfo roomBookInfo = roomBookInfoService.getOne(new QueryWrapper<RoomBookInfo>().eq("book_code",bookCode));
            if(!roomBookInfo.getBookStatus().equals("20")){
                throw new JeecgBootException("预定单号:" + roomBookInfo.getBookCode() +"当前状态不能取消分房!");
            }

            List<String> bookMxIdArr = Arrays.asList(bookMxIds.split(","));
            for(String bookMxId : bookMxIdArr){
                this.baseMapper.delete(new QueryWrapper<RoomBookRoom>().eq("book_mx_id", bookMxId)); //取消分配房间
            }

            //判断是不是全部明细取消分房，是的话变成已确认
            Long mxCnt = roomBookInfoMxService.count(new QueryWrapper<RoomBookInfoMx>().eq("book_code",bookCode));
            if(bookMxIdArr.size() == mxCnt){
                roomBookInfo.setBookStatus("10");
                roomBookInfoService.update(roomBookInfo, new QueryWrapper<RoomBookInfo>().eq("book_code", bookCode));
            }
        }
        catch (Exception e){
            throw e;
        }
    }

    /**
     * 通过bookCodes取消分房
     * @param bookCodes
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelFpByBookCode(String bookCodes) {

        try {
            List<String> bookCodeList = Arrays.asList(bookCodes.split(","));
            for (String bookCode : bookCodeList) {
                //校验状态
                RoomBookInfo roomBookInfo = roomBookInfoService.getOne(new QueryWrapper<RoomBookInfo>().eq("book_code",bookCode));
                if(!roomBookInfo.getBookStatus().equals("20")){
                    throw new JeecgBootException("预定单号:" + roomBookInfo.getBookCode() +"当前状态不能取消分房!");
                }
                //取消分房
                List<RoomBookInfoMx> roomBookInfoMxList = roomBookInfoMxService.list(new QueryWrapper<RoomBookInfoMx>().eq("book_code", bookCode));
                for(RoomBookInfoMx roomBookInfoMx : roomBookInfoMxList) {
                    this.baseMapper.delete(new QueryWrapper<RoomBookRoom>().eq("book_mx_id", roomBookInfoMx.getId())); //取消分配房间
                }

                //状态变为已确认
                roomBookInfo.setBookStatus("10");
                roomBookInfoService.update(roomBookInfo, new QueryWrapper<RoomBookInfo>().eq("book_code", bookCode));
            }
        }
        catch (Exception e){
            throw e;
        }
    }
}
